//
//  EcgRecordsVc.m
//  CareRingApp
//
//  Created by Linktop on 2024/5/7.
//

#import "EcgRecordsVc.h"
#import "ConfigModel.h"
#import <Masonry/Masonry.h>
#import <QMUIKit/QMUIKit.h>
#import "DeviceCenter.h"

#import "DBEcgRecord.h"
#import "EcgListCell.h"
#import "MainEcgVc.h"
#import "EcgDetailVc.h"
#import "TimeUtils.h"
#import "BasicCalendaVc.h"
#import <MJRefresh/MJRefresh.h>

@interface EcgRecordsVc ()<UITableViewDelegate, UITableViewDataSource>

@property(strong, nonatomic) UITableView *tableView;
@property(strong, nonatomic)NSMutableArray<DBEcgRecord *> *ecgRecArray;
@property(strong, nonatomic)NSDate *date;
@property(strong, nonatomic)UILabel *noDataTipLbl;

@end

@implementation EcgRecordsVc

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initUI];
}

-(void)initUI {

    self.navigationController.navigationBar.translucent = NO;
    
    self.navigationItem.title = [self.conclusionObj titleString];
    
    [self arrowback:nil];
    
    UIButton *navCalendaBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [navCalendaBtn setImage:[UIImage imageNamed:@"active_calenda"] forState:UIControlStateNormal];
    [navCalendaBtn addTarget:self action:@selector(gotoShowActiveCalenda:) forControlEvents:UIControlEventTouchUpInside];
    navCalendaBtn.backgroundColor = UIColor.blackColor;
    navCalendaBtn.frame = CGRectMake(0, 0, 44, 44);
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:navCalendaBtn];
    self.navigationItem.rightBarButtonItem = item;
    
    
//    QMUIButton *measuBtn = [[QMUIButton alloc]init];
//    [measuBtn setImage:[UIImage imageNamed:@"ecg_nav_btn"] forState:UIControlStateNormal];
//    [measuBtn addTarget:self action:@selector(gotoMeasure:) forControlEvents:UIControlEventTouchUpInside];
//    
//    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:measuBtn];
//    self.navigationItem.rightBarButtonItem = rightItem;
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.tableView.superview);
        make.top.equalTo(self.tableView.superview.mas_safeAreaLayoutGuideTop);
        make.bottom.equalTo(self.tableView.superview.mas_safeAreaLayoutGuideBottom);
    }];
    
    
    [self.tableView addSubview:self.noDataTipLbl];
    self.noDataTipLbl.hidden = YES;
    [self.noDataTipLbl mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.noDataTipLbl.superview.mas_centerX);
        make.centerY.equalTo(self.noDataTipLbl.superview.mas_centerY);
        make.width.lessThanOrEqualTo(self.noDataTipLbl.superview.mas_width);
    }];
    
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (!self.ecgRecArray.count) {
        // 初次查询
        [self queryData];
    }
}

-(void)queryData {
    NSNumber *conclusion = nil;
    NSDate *beginDate = nil;
    NSDate *endDate = nil;
    
    if (self.date) {
        beginDate = [TimeUtils zeroOfDate:self.date];
        endDate = [TimeUtils zeroOfNextDayDate:self.date];

    }
    
    if (self.conclusionObj.resTag != MAIN_ECG_RES_ALL_DATA) {
        conclusion = @(self.conclusionObj.resTag);
    }
    
    WEAK_SELF
    [DBEcgRecord queryByConclusion:[DeviceCenter instance].bindDevice.macAddress Conclusion:conclusion BeginDate:beginDate EndDate:endDate OrderBeTimeDesc:YES Cpmplete:^(NSMutableArray<DBEcgRecord *> * _Nonnull results) {
        STRONG_SELF
        strongSelf.ecgRecArray = results;
        [strongSelf.tableView reloadData];
        
        self.noDataTipLbl.hidden =  results.count > 0;
    }];
    
    
}

-(void)gotoShowActiveCalenda:(UIButton *)btn {
    
    // 日历选择
    BasicCalendaVc *calendaVc = [[BasicCalendaVc alloc]init];
    calendaVc.hidesBottomBarWhenPushed = YES;
    
    
//    calendaVc.evenQueryBlk = ^(void (^Blk)(NSMutableDictionary *dateKeys)) {
//        [DBEcgRecord queryAllDatesOrderByday:[DeviceCenter instance].bindDevice.macAddress BLK:^(NSMutableDictionary * _Nonnull dateKeys) {
//            if (Blk) {
//                Blk(dateKeys);
//            }
//        }];
//    };
//    
//    calendaVc.dateSelected = self.date ? self.date : [NSDate date] ;
//    
    WEAK_SELF
    calendaVc.selectDateCBK = ^(NSDate *date) {
        STRONG_SELF
        if (date) {
            strongSelf.date = date;
            [strongSelf queryData];
        }
    };
    
    [self presentViewController:calendaVc animated:YES completion:nil];
    
}

#pragma mark -- tableview
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.ecgRecArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1f;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 220.f;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    EcgListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EcgListCell" forIndexPath:indexPath];
//    cell.hmEcgDrawLineView.direction = [AccountCenter instance].currentAccount.otherInfo.wearHand.intValue;

    cell.ecgRecord = self.ecgRecArray[indexPath.row];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    EcgDetailVc *vc = [[EcgDetailVc alloc]init];
    vc.ecgRecord = self.ecgRecArray[indexPath.row];
    WEAK_SELF
    vc.deleteCBK = ^(DBEcgRecord * _Nonnull ecgRecord) {
        STRONG_SELF
        [strongSelf.ecgRecArray removeObject:ecgRecord];
        [strongSelf.tableView reloadData];
    };
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
    
}

#pragma mark --lazy

-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = UIColor.clearColor;
        _tableView.contentInset = UIEdgeInsetsZero;
//        [_tableView registerClass:[NormalSetCell class] forCellReuseIdentifier:@"mainecg_rescell"];
        [_tableView registerClass:[EcgListCell class] forCellReuseIdentifier:@"EcgListCell"];

        
        WEAK_SELF
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            STRONG_SELF
            // 下拉刷新列表
            if (strongSelf.date) {
                strongSelf.date = nil;
                [strongSelf queryData];
            }
            [strongSelf.tableView.mj_header endRefreshing];
        }];
        
        MJRefreshNormalHeader *header = (MJRefreshNormalHeader *)(_tableView.mj_header);
        header.lastUpdatedTimeLabel.hidden = YES;//控制是否显示上次加载时间label
        header.stateLabel.hidden = YES;//控制是否显示加载状态label
        
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0.0f;
        }
        
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
    }
    
    return _tableView;
}

-(UILabel *)noDataTipLbl
{
    if (!_noDataTipLbl) {
        _noDataTipLbl = [UILabel new];
        _noDataTipLbl.textAlignment = NSTextAlignmentCenter;
        _noDataTipLbl.textColor = SEPLINE_COLOR(1);
        _noDataTipLbl.font = [UIFont systemFontOfSize:16];
        _noDataTipLbl.numberOfLines = 2;
        _noDataTipLbl.adjustsFontSizeToFitWidth = YES;
        _noDataTipLbl.text = _L(L_NO_ECG_RECORDS);
    }
    return _noDataTipLbl;
}

@end
